import userServer from '../services/user';
import config from '../config';

const { globalSearchChatListDetail } = userServer;
const isPro = process.env.REACT_APP_ENV === 'pro'; // 正式环境
const { loginInfo } = config;
const webim = window.webim;

let selType = webim.RECENT_CONTACT_TYPE.GROUP;
let selToID = null; //当前选中聊天id（当聊天类型为私聊时，该值为好友帐号，否则为群号）
let selSess = null; //当前聊天会话对象
const typeZh = '群聊';
const recentSessMap = {}; //保存最近会话列表
const reqRecentSessCount = 200; //每次请求的最近会话条数，业务可以自定义

const maxNameLen = 12; //我的好友或群组列表中名称显示最大长度，仅demo用得到
const reqMsgCount = 100; //每次请求的历史消息(c2c获取群)条数，仅demo用得到

let myListeners = {}; // 保持自定义的回掉事件更新react数据

const options = {
  isAccessFormalEnv: true, //是否访问正式环境，默认访问正式，选填
  isLogOn: false, //是否开启控制台打印日志,默认开启，选填
};

function getBackendMsgText(elems) {
  const msgObj = {
    text: '',
    imgs: [],
  };
  if (!elems) return msgObj;
  let msgs = elems;
  if (typeof elems === 'string' && elems[0] === '[') msgs = JSON.parse(elems);
  // console.log('--back msgs--', msgs);
  if (msgs.length) {
    msgs.forEach((e) => {
      // 因为@消息和1账号文件提醒的消息都是TIMCustomElem这个类型
      if (e.msgType === 'TIMCustomElem') {
        const { Desc, Data, Ext } = e.msgContent;
        msgObj.type = Desc;
        if (Desc === 'file') {
          msgObj.newfilename = Ext; // newfilename.extension
        } else if (Desc === 'customer') {
          const extJson = JSON.parse(Ext);
          Object.assign(msgObj, extJson);
        } else if (Desc === 'customermsg') {
          if (Ext && Ext[0] === '{') {
            const extJson = JSON.parse(Ext);
            Object.assign(msgObj, extJson);
          }
        } else if (Desc === 'video') {
          // 不做处理
        } else if (Desc === 'at' || Desc.indexOf('@') > -1) {
          msgObj.text += `@${JSON.parse(Data).atlist[0].username}`;
        } else {
          msgObj.text += Desc;
        }
      } else if (e.msgType === 'TIMLocationElem') {
        msgObj.type = e.msgType;
        msgObj.text += JSON.parse(e.msgContent.Desc).address;
        msgObj.location = JSON.parse(e.msgContent.Desc);
      } else if (e.msgType === 'TIMImageElem') {
        msgObj.imgs.push(e.msgContent.ImageInfoArray[0].URL);
      } else if (e.msgType === 'TIMSoundElem') {
        msgObj.text = '暂不支持语音信息';
      } else {
        msgObj.text += e.msgContent.Text;
      }
    });
  }
  return msgObj;
}

function getMsgText(elems) {
  const msgs = elems || [];
  const msgObj = {
    text: '',
    imgs: [],
  };
  // console.log('---getMsgText---', elems);
  if (msgs.length) {
    msgs.forEach((e) => {
      // 因为@消息和1账号文件提醒的消息都是TIMCustomElem这个类型
      if (e.type === 'TIMCustomElem') {
        const { desc, data, ext } = e.content;
        msgObj.type = desc;
        if (desc === 'file') {
          msgObj.newfilename = ext; // newfilename.extension
        } else if (desc === 'customer') {
          const extJson = JSON.parse(ext);
          Object.assign(msgObj, extJson);
        } else if (desc === 'customermsg') {
          if (ext && ext[0] === '{') {
            const extJson = JSON.parse(ext);
            Object.assign(msgObj, extJson);
          }
        } else if (desc === 'video') {
          // 不做处理
        } else if (desc === 'at' || desc.indexOf('@') > -1) {
          msgObj.text += `@${JSON.parse(data).atlist[0].username}`;
        } else {
          msgObj.text += desc;
        }
      } else if (e.type === 'TIMLocationElem') {
        msgObj.type = e.type;
        msgObj.text += JSON.parse(e.content.desc).address;
        msgObj.location = JSON.parse(e.content.desc);
      } else if (e.type === 'TIMImageElem') {
        msgObj.imgs.push(e.content.ImageInfoArray[0].url);
      } else if (e.type === 'TIMSoundElem') {
        msgObj.text = '暂不支持语音信息';
      } else {
        msgObj.text += e.content.getText();
      }
    });
  }
  return msgObj;
}

function getLastMsgText(elems) {
  const msgs = elems || [];
  const msgObj = {
    text: '',
    imgs: [],
  };
  // console.log('---getLastMsgText---', elems);
  if (msgs.length) {
    msgs.forEach((e) => {
      if (e.MsgType === 'TIMCustomElem') {
        const { Desc, Data, Ext } = e.MsgContent;
        msgObj.type = Desc;
        if (Desc === 'file') {
          msgObj.newfilename = Ext; // newfilename.extension
        } else if (Desc === 'customer') {
          const extJson = JSON.parse(Ext);
          Object.assign(msgObj, extJson);
        } else if (Desc === 'customermsg') {
          if (Ext && Ext[0] === '{') {
            const extJson = JSON.parse(Ext);
            Object.assign(msgObj, extJson);
          }
        } else if (Desc === 'video') {
          // 不做处理
        } else if (Desc === 'at' || Desc.indexOf('@') > -1) {
          msgObj.text += `@${JSON.parse(Data).atlist[0].username}`;
        } else {
          msgObj.text += Desc;
        }
      } else if (e.MsgType === 'TIMLocationElem') {
        msgObj.type = e.MsgType;
        msgObj.text += JSON.parse(e.MsgContent.Desc).address;
      } else if (e.MsgType === 'TIMImageElem') {
        msgObj.imgs.push(e.MsgContent.ImageInfoArray[0].URL);
      } else if (e.MsgType === 'TIMSoundElem') {
        msgObj.text = '暂不支持语音信息';
      } else {
        msgObj.text += e.MsgContent.Text;
      }
    });
  }
  return msgObj;
}

// 先通过最后一条消息判断是否有@
function ifToBoMentioned(elems, fromAccount) {
  // 因为1账号也会发送自定义消息，并且结构跟前端发的不一样，所以要先排除
  if (fromAccount === '1') return false;

  if (!elems || !elems.length) return false;
  let has = false;
  for (let i = 0; i < elems.length; i++) {
    const msg = elems[i];
    const type = msg.MsgType || msg.type;
    const content = msg.MsgContent || msg.content;
    const desc = content.Desc || content.desc;
    if (type === 'TIMCustomElem' && desc !== 'video') {
      let data; // 兼容不同的数据结构
      if (msg.MsgContent) data = JSON.parse(msg.MsgContent.Data || '{}');
      else if (msg.content) data = JSON.parse(msg.content.data || '{}');

      if (data) {
        const atlist = data.atlist;
        const currentId = window.localStorage.getItem('userId');
        if (atlist.some((u) => u.userid === currentId)) {
          has = true;
          break;
        }
      }
    }
  }
  return has;
}

function onConnNotify(resp) {
  switch (resp.ErrorCode) {
    case webim.CONNECTION_STATUS.ON:
      console.log('--webim success--', resp);
      break;
    case webim.CONNECTION_STATUS.OFF:
      console.log('--webim unlink--', resp);
      myListeners.onChatImSdkError({
        message: '网络连接已断开，请检查网络',
        errFun: 'onConnNotify',
        ErrorCode: -99999,
      });
      break;
    case webim.CONNECTION_STATUS.RECONNECT:
      console.log('--webim normal--', resp);
      myListeners.onChatImSdkError({
        message: '网络已重新连接',
        errFun: 'onConnNotify',
        ErrorCode: 99999,
      });
      recentContact(); // 重新加载数据
      if (selToID) createChatInstance(selType, selToID);
      break;
    default:
      console.log('--webim unkone--', resp);
      break;
  }
}

const onGroupSystemNotifys = {
  4: onKickedGroupNotify, //被管理员踢出群(只有被踢者接收到)
  15: onReadedSyncGroupNotify, // 群消息已读同步通知
};
//监听事件
const baseListeners = {
  onConnNotify: onConnNotify, // 监听连接状态回调变化事件,必填
  onMsgNotify: onMsgNotify, // 监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
  onGroupSystemNotifys: onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，如果不需要监听，可不填
  onLongPullingNotify: function (data) {
    console.debug('onLongPullingNotify', data);
  },
};

// 初始化webimsdk
function init(successCB, errorCB, _myListeners, listeners) {
  myListeners = _myListeners;
  
  let netstate = window.localStorage.getItem('netstate');
  if (netstate == 'offline') {
    recentContact();
    return
  }
  webim.logout();
  webim.login(
    {
      ...loginInfo,
      identifier: window.localStorage.getItem('userId'),
      userSig: window.localStorage.getItem('userSig'),
    },
    { ...baseListeners, ...listeners },
    options,
    function (resp) {
      console.log('3333333333333333333',resp)
      successCB && successCB(resp);
      // 初始化成功默认加载最近聊天记录
      recentContact();
    },
    function (err) {
      console.log('3333333333333333333',err)
      errorCB && errorCB(err);
    }
  );
}

// 同步App的的消息已读操作
function onKickedGroupNotify(notify) {
  recentContact(); // 重新加载数据
  if (selToID === notify.GroupId) {
    myListeners.onKickedToClearChatInstance();
  }
}

// 同步App的的消息已读操作
function onReadedSyncGroupNotify(notify) {
  const { GroupId } = notify;
  const sessKey = `GROUP_${GroupId}`;
  const recentSess = recentSessMap[sessKey];
  console.log('--onReadedSyncGroupNotify-out--');
  if (recentSess) {
    const UnreadMsgCount = recentSess.UnreadMsgCount;
    if (UnreadMsgCount > 0) {
      console.log('--onReadedSyncGroupNotify-inner--', GroupId, recentSess);
      recentSessMap[sessKey].UnreadMsgCount = 0;
      recentSessMap[sessKey].Mentioned = false;
      // 更新消息计数 不需要再请求接口，参数2传false
      myListeners.onChatListChange(recentSessMap, false);
    }
  }
}

// 获取最近联系人
function recentContact() {
  let netstate = window.localStorage.getItem('netstate');
  if (netstate == 'offline') {
    let aa = window.localStorage.getItem('recentSessMap');
    myListeners.onChatListChange(JSON.parse(aa), true);
    return
  }
  webim.getRecentContactList(
    {
      Count: reqRecentSessCount, //要拉取的最近会话条数
    },
    function (resp) {
      // console.log(resp,'2222222222222222');
      let tempSess; //临时会话变量
      // console.log('----getRecentConta1ctList success---', resp);
      const unReadSess = [];
      if (resp.SessionItem && resp.SessionItem.length > 0) {
        //如果存在最近会话记录
        for (let i in resp.SessionItem) {
          const item = resp.SessionItem[i];
          const type = item.Type; //接口返回的会话类型
          let sessType,
            sessionId,
            sessionNick = '',
            senderId = '',
            senderNick = '';
          if (type === webim.RECENT_CONTACT_TYPE.GROUP) {
            //群聊
            sessType = webim.SESSION_TYPE.GROUP; //设置会话类型
            sessionId = item.ToAccount; //会话id，群聊时为群ID，注意：从ToAccount获取
            sessionNick = item.GroupNick; //会话昵称，群聊时，为群名称，接口一定会返回
            senderId = item.MsgGroupFrom_Account; //群消息的发送者id
            senderNick = item.MsgGroupFromNickName; //群消息的发送者名称

            if (!senderId) {
              //发送者id为空
              webim.Log.warn('群消息发送者id为空,senderId=' + senderId + ',groupid=' + sessionId);
              continue;
            }
            if (senderId === '@TIM#SYSTEM') {
              //先过滤群系统消息，因为接口暂时区分不了是进群还是退群等提示消息，
              webim.Log.warn('过滤群系统消息,senderId=' + senderId + ',groupid=' + sessionId);
              continue;
            }
          }

          if (!sessionId) {
            //会话id为空
            webim.Log.warn('会话id为空,sessionId=' + sessionId);
            continue;
          }

          if (sessionId === '@TLS#NOT_FOUND') {
            //会话id不存在，可能是已经被删除了
            webim.Log.warn('会话id不存在,sessionId=' + sessionId);
            continue;
          }

          if (sessionNick.length > maxNameLen) {
            //帐号或昵称过长，截取一部分，出于demo需要，业务可以自己决定
            sessionNick = sessionNick.substr(0, maxNameLen) + '...';
          }

          tempSess = recentSessMap[sessType + '_' + sessionId];
          if (!tempSess) {
            //先判断是否存在（用于去重），不存在增加一个

            recentSessMap[sessType + '_' + sessionId] = {
              typeZh,
              SessionType: sessType, //会话类型
              SessionId: sessionId, //会话对象id，好友id或者群id
              SessionNick: sessionNick, //会话昵称，好友昵称或群名称
              C2cAccount: senderId, //发送者id，群聊时，才有用
              C2cNick: senderNick, //发送者昵称，群聊时，才有用
              UnreadMsgCount: item.UnreadMsgCount, //未读消息数,私聊时需要通过webim.syncMsgs(initUnreadMsgCount)获取,参考后面的demo，群聊时不需要。
              MsgSeq: item.MsgSeq, //消息seq
              MsgRandom: item.MsgRandom, //消息随机数
              MsgTimeStamp: item.MsgTimeStamp, //消息时间戳
              MsgGroupReadedSeq: item.MsgGroupReadedSeq || 0,
              MsgShow: getLastMsgText(item.LastMsg.MsgBody), //消息内容,文本消息为原内容，表情消息为[表情],其他类型消息以此类推
              Mentioned: item.UnreadMsgCount < 1 ? false : ifToBoMentioned(item.LastMsg.MsgBody, senderId), // 首先根据最后一条消息判断是否有@
            };
          }

          // 获取有未读消息的最近会话
          if (item.UnreadMsgCount > 1) {
            unReadSess.push({
              GroupId: sessionId,
              ReqMsgNumber: item.UnreadMsgCount,
            });
          }
        }
      }
      // console.log('--recentSessMap-recentSessMap-recentSessMap-', recentSessMap);

      // 如果有多个未读，请求各自聊天记录查看是否有@
      if (unReadSess.length) {
        const promises = unReadSess.map((r) => getGroupHistoryMsg(r));
        Promise.all(promises)
          .then((res) => {
            for (let oi = 0; oi < res.length; oi++) {
              const key = `${webim.SESSION_TYPE.GROUP}_${unReadSess[oi].GroupId}`;
              const inmsgs = res[oi];
              const Mentioned = inmsgs.some((im) => ifToBoMentioned(im.elems, im.fromAccount));
              recentSessMap[key].Mentioned = Mentioned;
              break;
            }
            myListeners.onChatListChange(recentSessMap, true);
          })
          .catch((err) => {
            myListeners.onChatImSdkError({ message: `获取聊天记录失败-${err.message}`, errFun: 'recentContact' });
          });
        return;
      }
      window.localStorage.setItem('recentSessMap', JSON.stringify(recentSessMap));
      myListeners.onChatListChange(recentSessMap, true);
    },
    function (resp) {
      console.log('----getRecentContactList err---', resp);
    }
  );
}

// 有消息更新 返回的是新消息数组，结构为[Msg]
function onMsgNotify(newMsgList) {
  // console.log('--onMsgNotify--', newMsgList);
  for (var j in newMsgList) {
    //遍历新消息
    const item = newMsgList[j];
    // console.log('--onMsgNotify--', item, item.getSession());

    // 如果是系统消息直接不做任何处理, 并且设置为已读
    if (item.fromAccount === '@TIM#SYSTEM') {
      webim.setAutoRead(item.getSession(), true, true);
      return;
    }

    const sessionId = item.getSession().id();
    const sessType = item.getSession().type();
    let tempSess = recentSessMap[sessType + '_' + sessionId];
    const MsgShow = getMsgText(item.elems);
    // 新增或者修改 项目或者任务 任何内容1的帐号都会推送通知，根据消息内容做页面刷新同步(缺陷：没做收集更新处理，可能导致页面重复更新)
    if (item.fromAccount === '1') {
      myListeners.onNewMsgByOneToUpdate(MsgShow, sessionId);
    }

    if (!tempSess) {
      // 最近联系人里面没有该联系人，就创建一个
      tempSess = {
        typeZh,
        UnreadMsgCount: 0,
      };
    }

    recentSessMap[sessType + '_' + sessionId] = {
      ...tempSess,
      typeZh,
      UnreadMsgCount: tempSess.UnreadMsgCount + 1,
      SessionType: sessType, //会话类型
      SessionId: sessionId, //会话对象id，好友id或者群id
      SessionNick: item.sessionNick, //会话昵称，好友昵称或群名称
      C2cAccount: item.fromAccount, //发送者id，群聊时，才有用
      C2cNick: item.fromAccountNick, //发送者昵称，群聊时，才有用
      MsgSeq: item.seq, //消息seq
      MsgRandom: item.random, //消息随机数
      MsgTimeStamp: item.time, //消息时间戳
      MsgGroupReadedSeq: item.MsgGroupReadedSeq || 0,
      MsgShow, //消息内容,文本消息为原内容，表情消息为[表情],其他类型消息以此类推
    };

    if (sessionId === selToID) {
      //为当前聊天对象的消息
      // 在聊天窗体中新增一条消息, 和自动设置消息已读; 并且屏蔽系统消息
      myListeners.onChatMsgsChange(selToID, [item]);
      webim.setAutoRead(selSess, true, true);
      recentSessMap[sessType + '_' + sessionId].UnreadMsgCount = 0;
      recentSessMap[sessType + '_' + sessionId].Mentioned = false;
    } else {
      // 其它聊天设置@提示
      if (!recentSessMap[sessType + '_' + sessionId].Mentioned) {
        const Mentioned = ifToBoMentioned(item.elems, item.fromAccount);
        recentSessMap[sessType + '_' + sessionId].Mentioned = Mentioned;
      }
      // 保存其它聊天的新消息 因为webim.syncGroupMsgs不会返回新的聊天信息;  并且屏蔽系统消息
      myListeners.onChatOtherMsgsChange();
    }
  }

  // 更新聊天列表(缺陷：没做收集更新处理，可能导致页面重复更新)
  myListeners.onChatListChange(recentSessMap, true);
}

function getHistoryDataCallbackForWeb(callbackChatData, prepage) {
  // 在聊天窗体中新增一条消息
  myListeners.onChatMsgsChange(selToID, callbackChatData, prepage);
  let netstate = window.localStorage.getItem('netstate');
  if (netstate == 'online') {
    // 消息已读上报，并将当前会话的消息设置成自动已读
    webim.setAutoRead(selSess, true, true);
    // 更新recentSessMap的未读数和@状态
    recentSessMap[selType + '_' + selToID].UnreadMsgCount = 0;
    recentSessMap[selType + '_' + selToID].Mentioned = false;
    // 更新消息计数 不需要再请求接口，参数2传false
    myListeners.onChatListChange(recentSessMap, false);
  }
}

// 切换聊天组，实例化当前聊天, 拉取聊天记录
function createChatInstance(sess_type, to_id) {
  // 清除之前的聊天
  if (selToID) webim.MsgStore.delSessByTypeId(selType, selToID);

  selType = sess_type || webim.SESSION_TYPE.GROUP;
  selToID = to_id; //初始化当前聊天对象id
  selSess = webim.MsgStore.sessByTypeId(selType, selToID); // 先从最近会话里面找
  if (!selSess) {
    // 否则创建新会话对象
    selSess = new webim.Session(selType, selToID, selToID);
  }
  let netstate = window.localStorage.getItem('netstate');
  if (netstate == 'offline') {
    if (!isPro) {
      let message =  window.localStorage.getItem('chatMessage-'+selToID);
      if(message){
        message = JSON.parse(message);
        getHistoryDataCallbackForWeb(message.data, false);
      }
    }else{
      let message =  window.localStorage.getItem('chatDevMessage-'+selToID);
      if(message){
        message = JSON.parse(message);
        getHistoryMsgCallback(message);
      }
    }
    return
  }
  // console.log('--createChatInstance--', selSess, webim.MsgStore.sessMap());
  getGroupInfo(selToID, function (resp) {
    //拉取最新的群历史消息
    const ReqMsgSeq = resp.GroupInfo[0].NextMsgSeq - 1;
    const options = {
      GroupId: selToID,
      ReqMsgSeq,
      ReqMsgNumber: reqMsgCount,
    };
    if (options.ReqMsgSeq === null || options.ReqMsgSeq === undefined || options.ReqMsgSeq <= 0) {
      webim.Log.warn('该群还没有历史消息:options=' + JSON.stringify(options));
      return;
    }

    const tempSess = recentSessMap[selType + '_' + selToID] || {};
    recentSessMap[selType + '_' + selToID] = {
      MsgTimeStamp: 0,
      ...tempSess,
      MsgGroupReadedSeq: ReqMsgSeq,
      SessionId: selToID,
    };
    // 由于syncGroupMsg不会返回最新的未读消息，正式环境要拿后台的数据
    if (!isPro) {
      const params = {
        groupid: selToID,
        msgseqbegin: ReqMsgSeq - reqMsgCount < 1 ? 1 : ReqMsgSeq - reqMsgCount,
        msgseqend: ReqMsgSeq + 1,
      };
      globalSearchChatListDetail(params)
        .then((listRes) => {
          // console.log('--listRes--', listRes);
          window.localStorage.setItem('chatMessage-' + selToID, JSON.stringify(listRes));
          getHistoryDataCallbackForWeb(listRes.data, false);
        })
        .catch((listErr) => {
          myListeners.onChatImSdkError({ ...listErr, message: listErr.message, errFun: 'createChatInstance' });
        });
    } else {
      webim.syncGroupMsgs(
        options,
        function (msgList) {
          // console.log('-----syncGroupMsgs----', msgList, ReqMsgSeq);
          if (msgList.length === 0) {
            webim.Log.warn('该群没有历史消息了:options=' + JSON.stringify(options));
            getHistoryDataCallbackForWeb([], false);
            return;
          }
          window.localStorage.setItem('chatDevMessage-' + selToID, JSON.stringify(msgList));
          getHistoryMsgCallback(msgList);
          // 一次只能拉取20条记录，递归全部消息
          console.log('--------------一次只能拉取20条记录，递归全部消息----------------------');
          if(msgList.length >= 20){
            getTotalHistoryMsg(options, ReqMsgSeq - 20);
          }
        },
        function (err) {
          myListeners.onChatImSdkError({ ...err, message: err.SrcErrorInfo, errFun: 'createChatInstance' });
        }
      );
    }
  });
}

function getTotalHistoryMsg(data, ReqMsgSeq) {
  const options = { ...data, ReqMsgSeq: ReqMsgSeq };
  webim.syncGroupMsgs(
    options,
    function (msgList) {
      console.log('-----getTotalHistoryMsg----', msgList, options);
      if (msgList.length === 0) {
        return;
      }
      const callbackChatData = [];
      let msg;
      for (let j in msgList) {
        //遍历新消息
        msg = msgList[j];
        if (msg.getSession().id() === selToID) {
          //为当前聊天对象的消息
          selSess = msg.getSession();
          // 在聊天窗体中新增一条消息; 并且屏蔽系统消息
          if (msg.fromAccount !== '@TIM#SYSTEM') callbackChatData.push(msg);
        }
      }
      myListeners.onChatMsgsHistory(selToID, callbackChatData);
      if(msgList.length >= 20){
        getTotalHistoryMsg(options, ReqMsgSeq - 20);
      }
    },
    function (err) {
      myListeners.onChatImSdkError({ ...err, message: err.SrcErrorInfo, errFun: 'createChatInstance' });
    }
  );
}

//读取群组基本资料-高级接口
function getGroupInfo(group_id, cbOK, cbErr) {
  var options = {
    GroupIdList: [group_id],
    GroupBaseInfoFilter: [
      'Type',
      'Name',
      'Introduction',
      'Notification',
      'FaceUrl',
      'CreateTime',
      'Owner_Account',
      'LastInfoTime',
      'LastMsgTime',
      'NextMsgSeq',
      'MemberNum',
      'MaxMemberNum',
      'ApplyJoinOption',
      'ShutUpAllMember',
    ],
    MemberInfoFilter: ['Account', 'Role', 'JoinTime', 'LastSendMsgTime', 'ShutUpUntil'],
  };
  webim.getGroupInfo(
    options,
    function (resp) {
      if (resp.GroupInfo[0].ShutUpAllMember === 'On') {
        myListeners.onChatImSdkError({ message: '该群组已开启全局禁言', errFun: 'getGroupInfo1' });
      }
      if (cbOK) {
        cbOK(resp);
      }
    },
    function (err) {
      myListeners.onChatImSdkError({ ...err, message: err.ErrorInfo, errFun: 'getGroupInfo2' });
    }
  );
}

// 获取历史消息的回掉
function getHistoryMsgCallback(msgList, prepage) {
  let msg;
  prepage = prepage || false;

  //如果是加载前几页的消息，消息体需要prepend，所以先倒排一下
  if (prepage) {
    msgList.reverse();
  }

  const callbackChatData = [];
  for (let j in msgList) {
    //遍历新消息
    msg = msgList[j];
    if (msg.getSession().id() === selToID) {
      //为当前聊天对象的消息
      selSess = msg.getSession();
      // 在聊天窗体中新增一条消息; 并且屏蔽系统消息
      if (msg.fromAccount !== '@TIM#SYSTEM') callbackChatData.push(msg);
    }
  }

  getHistoryDataCallbackForWeb(callbackChatData, prepage);
}

function sendMsg(msgContent, callback) {
  var msgLen = webim.Tool.getStrBytes(msgContent);

  if (msgContent.length < 1) {
    myListeners.onChatImSdkError({ message: '发送的消息不能为空!', errFun: 'sendMsg1' });
    return;
  }

  let maxLen, errInfo;
  if (selType === webim.SESSION_TYPE.C2C) {
    maxLen = webim.MSG_MAX_LENGTH.C2C;
    errInfo = '消息长度超出限制(最多' + Math.round(maxLen / 3) + '汉字)';
  } else {
    maxLen = webim.MSG_MAX_LENGTH.GROUP;
    errInfo = '消息长度超出限制(最多' + Math.round(maxLen / 3) + '汉字)';
  }
  if (msgLen > maxLen) {
    myListeners.onChatImSdkError({ message: errInfo, errFun: 'sendMsg2' });
    return;
  }
  //发消息处理
  handleMsgSend(msgContent, callback);
}

function createMsg() {
  const isSend = true; //是否为自己发送
  const seq = -1; //消息序列，-1表示sdk自动生成，用于去重
  const random = Math.round(Math.random() * 4294967296); //消息随机数，用于去重
  const msgTime = Math.round(new Date().getTime() / 1000); //消息时间戳
  let subType; //消息子类型
  if (selType === webim.SESSION_TYPE.C2C) {
    subType = webim.C2C_MSG_SUB_TYPE.COMMON;
  } else {
    //webim.GROUP_MSG_SUB_TYPE.COMMON-普通消息,
    //webim.GROUP_MSG_SUB_TYPE.LOVEMSG-点赞消息，优先级最低
    //webim.GROUP_MSG_SUB_TYPE.TIP-提示消息(不支持发送，用于区分群消息子类型)，
    //webim.GROUP_MSG_SUB_TYPE.REDPACKET-红包消息，优先级最高
    subType = webim.GROUP_MSG_SUB_TYPE.COMMON;
  }
  return new webim.Msg(selSess, isSend, seq, random, msgTime, loginInfo.identifier, subType, loginInfo.identifierNick);
}

function handleMsgSend(msgContent, callback) {
  const msg = createMsg();
  var text_obj, face_obj, tmsg, emotionIndex, emotion, restMsgIndex;
  //解析文本和表情
  var expr = /\[[^[\]]{1,3}\]/gm;
  var emotions = msgContent.match(expr);
  if (!emotions || emotions.length < 1) {
    text_obj = new webim.Msg.Elem.Text(msgContent);
    msg.addText(text_obj);
  } else {
    for (var i = 0; i < emotions.length; i++) {
      tmsg = msgContent.substring(0, msgContent.indexOf(emotions[i]));
      if (tmsg) {
        text_obj = new webim.Msg.Elem.Text(tmsg);
        msg.addText(text_obj);
      }
      emotionIndex = webim.EmotionDataIndexs[emotions[i]];
      emotion = webim.Emotions[emotionIndex];

      if (emotion) {
        face_obj = new webim.Msg.Elem.Face(emotionIndex, emotions[i]);
        msg.addFace(face_obj);
      } else {
        text_obj = new webim.Msg.Elem.Text(emotions[i]);
        msg.addText(text_obj);
      }
      restMsgIndex = msgContent.indexOf(emotions[i]) + emotions[i].length;
      msgContent = msgContent.substring(restMsgIndex);
    }
    if (msgContent) {
      text_obj = new webim.Msg.Elem.Text(msgContent);
      msg.addText(text_obj);
    }
  }

  msg.sending = 1;
  msg.originContent = msgContent;

  webim.sendMsg(
    msg,
    function (resp) {
      //发送成功，把send loading清理
      // 在聊天窗体中新增一条消息, 消息发送成功会触发onMsgNotify
      // callback清空输入框
      callback();
    },
    function (err) {
      //提示重发
      showReSend(msg);
    }
  );
}

function showReSend(msg) {
  console.log('---showReSend---', msg);
  //发消息处理
  // handleMsgSend(msg.originContent);
}

//发送自定义消息

function sendCustomMsg(msgsArr, callback) {
  const msg = createMsg();
  msgsArr.forEach((m) => {
    const { type, content } = m;
    if (type === 'TIMTextElem') {
      const text_obj = new webim.Msg.Elem.Text(content.text);
      msg.addText(text_obj);
    } else if (type === 'TIMCustomElem') {
      const { data, desc, ext } = content;
      const custom_obj = new webim.Msg.Elem.Custom(data, desc, ext);
      msg.addCustom(custom_obj);
    }
  });
  //调用发送消息接口
  msg.sending = 1;
  webim.sendMsg(
    msg,
    function (resp) {
      //发送成功，把send loading清理
      // 在聊天窗体中新增一条消息, 消息发送成功会触发onMsgNotify
      // callback清空输入框
      callback();
    },
    function (err) {
      myListeners.onChatImSdkError({ ...err, message: err.ErrorInfo, errFun: 'sendCustomMsg' });
    }
  );
}

// 读取群组成员资料， 但是没有成员名称
function getGroupMembers({ GroupId, withCurrentUser }, callback) {
  var options = {
    GroupId,
    Offset: 0, //必须从 0 开始
    Limit: 5999,
    MemberInfoFilter: ['Account'],
  };
  webim.getGroupMemberInfo(
    options,
    function (resp) {
      if (resp.MemberNum <= 0) {
        myListeners.onChatImSdkError({ message: '该群组目前没有成员', errFun: 'getGroupMembers' });
        return;
      } else if (resp.MemberNum === 1) {
        if (callback) callback([]);
        return;
      }
      const users = []; // string Array
      const currentId = window.localStorage.getItem('userId');
      for (var i in resp.MemberList) {
        const userid = resp.MemberList[i].Member_Account;
        if (currentId === userid && !withCurrentUser) {
          continue;
        }
        users.push(userid);
      }

      const tag_list = ['Tag_Profile_IM_Nick', 'Tag_Profile_IM_Image'];
      const options = {
        To_Account: users,
        TagList: tag_list,
      };

      const linkObj = {
        Tag_Profile_IM_Nick: 'username',
        Tag_Profile_IM_Image: 'headimage',
      };

      // 再根据用户id或者用户呢称
      webim.getProfilePortrait(
        options,
        function (resp) {
          if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
            const groupUsersInfo = [];
            resp.UserProfileItem.forEach((v) => {
              const user = { userid: v.To_Account };
              v.ProfileItem && v.ProfileItem.forEach((p) => (user[linkObj[p.Tag]] = p.Value));
              groupUsersInfo.push(user);
            });
            if (callback) callback(groupUsersInfo);
          }
        },
        function (err) {
          myListeners.onChatImSdkError({ ...err, message: err.SrcErrorInfo, errFun: 'getProfilePortrait' });
        }
      );
    },
    function (err) {
      myListeners.onChatImSdkError({ ...err, message: err.ErrorInfo, errFun: 'getGroupMemberInfo' });
    }
  );
}

function getGroupHistoryMsg({ GroupId, ReqMsgNumber }) {
  //拉取最新的群历史消息
  return new Promise((res, ret) => {
    const options = {
      GroupId,
      ReqMsgNumber,
    };
    webim.syncGroupMsgs(options, res, function (err) {
      myListeners.onChatImSdkError({ ...err, message: err.SrcErrorInfo, errFun: 'getGroupHistoryMsg' });
      ret(err);
    });
  });
}

export default {
  init,
  recentContact,
  createChatInstance,
  sendMsg,
  sendCustomMsg,
  getMsgText,
  getBackendMsgText,
  getGroupMembers,
};
